<?php
/**
 * 设备数据同步接口
 */
namespace App\HttpController\Api\Device;

use App\Lib\Utils;

use App\Model\Attend\Group as AttendGroupModel;
use App\Model\Attend\AttendSend as AttendSendModel;
use App\Model\Attend\Calendar as CalendarModel;
use App\Model\Attend\Schedule as ScheduleModel;
use App\Model\Attend\Classes as ClassesModel;

use EasySwoole\Component\Di;
use App\Lib\Redis\Redis;
use EasySwoole\Component\Timer;
use EasySwoole\Http\Message\Status;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;

// 设备相关模型
use App\Model\Device\DeviceModel as DeviceModel;
use App\Model\Device\DeviceInfoModel as InfoModel;
use App\Model\Device\DeviceLogModel as LogModel;

// 人脸信息模型
use App\Model\Face\CompareModel;
use App\Model\Face\CompareInfoModel;


use App\Model\Admin\User as UserModel;
use App\Model\Monitor\Rules as MonitorRulesModel;
use App\Model\Monitor\Log as MonitorLogModel;
use App\Model\Face\FaceModel as FaceModel;
use App\Model\System\WxConfig as WxConfigModel;
use App\Model\Monitor\TemperRules as TemperRulesModel;
use App\Model\Monitor\TemperLog as TemperLogModel;

use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\FastCache\Cache;

use App\HttpController\LogHandel;

use EasySwoole\EasySwoole\Logger;

use App\Lib\Curl;
use App\Lib\WeChat;

class Compareinfo extends \App\HttpController\Api\ApiBase
{

    public $logger;
    public $DeviceId;
    public $DeviceUUID;

    public $configPath;
    public $configBaseBt;

    public $deviceObj;
    public $infoObj;
    public $logObj;
    public $compareObj;
    public $compareInfoObj;

    public function index()
    {
        try {
            // 1. 基础验证
            $logger = new LogHandel();
            $logger->log("接收设备记录开始", LogHandel::LOG_LEVEL_INFO, 'DeviceCompareinfo');

            $this->logger = $logger;
            $this->deviceObj = new DeviceModel();
            $this->infoObj = new InfoModel();
            $this->logObj = new LogModel();

            $this->compareObj = new CompareModel();
            $this->compareInfoObj = new CompareInfoModel();

            //$configPath = \Yaconf::get('path');
            $this->configPath = $this->getConfig('path');
            $this->configBaseBt = $this->getConfig('basebt');

            $getData = $this->raw;
            $actData = json_decode(Utils::characet($getData),true);
            $testData = $actData;

            $sIP = $this->ip;
            $sPort = $this->port;

            if (!isset($actData['Name']) || empty($actData['Name'])) {
                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
            }

            if ($actData['Name'] != 'captureInfoRequest') {
                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
            }

            $retArray = array();
            $retArray['Name'] = 'captureInfoResponse';
            $retArray['TimeStamp'] = time();
            $retArray['Code'] = 1;
            $retArray['Message'] = 'ok';

            $DeviceId = "";
            if (isset($actData['DeviceId'])) {
                $DeviceId = trim(str_replace(array("\r\n", "\r", "\n"), "", $actData['DeviceId']));
            }

            $DeviceUUID = "";
            if (isset($actData['UUID'])) {
                $DeviceUUID = trim(str_replace(array("\r\n", "\r", "\n"), "", $actData['UUID']));
            }

            if ((!isset($DeviceUUID) || empty($DeviceUUID))) {

                $logger->log("接收设备记录错误：UUID不存在", LogHandel::LOG_LEVEL_ERROR, 'DeviceCompareinfo');

                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
            }

            $dev_where['A.device_id'] = $DeviceId;
            $dev_where['A.device_uuid'] = $DeviceUUID;
            $deviceInfo = $this->deviceObj->getDeviceInfo('*', $dev_where);

            if (!$deviceInfo || !is_array($deviceInfo)) {

                $logger->log("接收设备记录错误：找不到设备", LogHandel::LOG_LEVEL_ERROR, 'DeviceCompareinfo');

                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", []);
            }

            $this->DeviceId = $DeviceId;
            $this->DeviceUUID = $DeviceUUID;

            // 2. 业务处理
            $data = [
                'device_id' => $DeviceId,
                'device_remark' => $DeviceUUID
            ];

            $data = $this->makeData($actData, $data);
            $h_result = $this->captureHandler($actData, $data, $deviceInfo, $retArray);

            if ($h_result['error'] > 0) {
                return $this->writeJsonDev($h_result['data']);
            }

            $retArray['Session'] = $deviceInfo['session'];

            $data = $h_result['data']['data'];
            $info = $h_result['data']['info'];

            //$this->pushMessage($data, $deviceInfo);

            $logger->log("接收设备记录结束", LogHandel::LOG_LEVEL_INFO, 'DeviceCompareinfo');

            return $this->writeJsonDev($retArray);

        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
        }
    }

    // 基础数据构建
    public function makeData($actData, $data)
    {
        $di = isset($actData['Data']['DeviceInfo']) ? $actData['Data']['DeviceInfo'] : [];
        $ti = isset($actData['Data']['TemperaInfo']) ? $actData['Data']['TemperaInfo'] : [];

        $DeviceUUID = trim(str_replace(array("\r\n", "\r", "\n"), "", $di['DeviceUUID']));

        $data['device_uuid'] = $DeviceUUID;

        // NVR通道号
        if (isset($di['ChannelNo']) && is_numeric($di['ChannelNo']) ) {
            $data['channel'] = intval($di['ChannelNo']);
        }else{
            $data['channel'] = 0;
        }

        // 设备连接的子设备ip地址
        if (isset($di['SubDeviceInfo']['SubDeviceIP'])) {
            $data['sub_device_ip'] = $di['SubDeviceInfo']['SubDeviceIP'];
        } else {
            if (isset($di['DeviceIP'])) {
                $data['ip'] = $di['DeviceIP'];
            } else {
                $data['ip'] = '';
            }
        }

        // 抓拍人脸体温
        if (!empty($ti)) {
            if (isset($ti['Temperature'])) {
                $data['temper'] = $ti['Temperature'];
            }
            if (isset($ti['EnvirTemperature'])) {
                $data['etemper'] = $ti['EnvirTemperature'];
            }
        }
        return $data;
    }

    // 比对信息处理
    public function compareHandler($ci, &$data, &$info)
    {
        // 报警事件 0：不报警 1：黑名单报警 2：白名单报警 3：VIP名单报警 4：非白名单报警
        if (isset($ci['AlarmEvent'])) {
            $info['alarm_event'] = $ci['AlarmEvent'];
        }

        // 人脸活体检测 0：非活体 1： 活体
        if (isset($ci['Liveness'])) {
            $data['liveness'] = $ci['Liveness'];
        }

        // 人脸属性
        if (isset($ci['Attribute'])) {

            $attr = $ci['Attribute'];

            if (isset($attr['Age'])) {
                $info['attr_age'] = $attr['Age']; // 识别年龄
            }

            if (isset($attr['Gender'])) {
                $info['attr_gender'] = $attr['Gender']; // 识别性别
            }

            if (isset($attr['Glasses'])) {
                $info['attr_glasses'] = $attr['Glasses']; // 是否带银镜
            }

            if (isset($attr['Mask'])) {
                $info['attr_mask'] = $attr['Mask']; // 是否戴面具
            }

            if (isset($attr['Beard']) ) {
                $info['attr_beard'] = $attr['Beard']; // 是否留胡子
            }

            if (isset($attr['Race']) ) {
                $info['attr_race'] = $attr['Race']; // 肤色 1黄种人，2黑种人，3白种人
            }

            if (isset($attr['Motion'])) {
                $info['attr_emotion'] = $attr['Motion'];	// 表情 [1:生气 2:平静 3:高兴 4:悲伤5:惊讶];
            }
        }

        // 名单类型：0：陌生人 1：黑名单  2：白名单 3：VIP名单 根据此值判断是否比对成功
        if (isset($ci['PersonType'])) {
            $data['person_type'] = $ci['PersonType'];
        } else {
            $data['person_type'] = 0;
        }

        // 比对成功计数
        if (isset($ci['VisitsCount'])) {
            $info['visit_count'] = $ci['VisitsCount'];
        }

        // 相似度
        if (isset($ci['Similarity'])) {
            $data['compare_result'] = $ci['Similarity'];
        } else {
            $data['compare_result'] = 0;
        }

        // 个人信息
        if (isset($ci['PersonInfo'])) {
            $pi = $ci['PersonInfo'];

            if (isset($pi['PersonName'])) {
                $data['name'] = trim($pi['PersonName']);
            } else {
                $data['name'] = '';
            }
            if (isset($pi['PersonId'])) {
                $data['face_id'] = trim($pi['PersonId']);
            } else {
                $data['face_id'] = 0;
            }
        } else {
            $data['face_id'] = 0;
        }
    }

    // 处理摄像头捕捉信息
    public function captureHandler($actData, $data, $deviceInfo, $retArray)
    {
        global $_W;

        $result = ['error' => 0];
        $info = [];
        $ci = isset($actData['Data']['CaptureInfo']) ? $actData['Data']['CaptureInfo'] : [];
        $di = isset($actData['Data']['DeviceInfo']) ? $actData['Data']['DeviceInfo'] : [];

        if (isset($di['DeviceMac'])) {
            $info['device_mac'] = $di['DeviceMac'];
        }

        // 抓拍上传的发送时间
        if (isset($ci['SendTime'])) {
            $data['send_time'] = strtotime($ci['SendTime']);
        }

        // 抓拍时间
        if (isset($ci['CaptureTime'])) {
            $data['capture_time'] = strtotime($ci['CaptureTime']);
            if ($data['capture_time'] <= strtotime('1970-01-01')) {
                $data['capture_time'] = strtotime('1970-01-01');
            }
        }

        // 该设备的总访问次数
        if (isset($ci['CaptureCount'])) {
            $info['visit_count'] = $ci['CaptureCount'];
        }

        $data['imgpath'] = "0";
        $data['imgexpath'] = "0";

        // 存储人脸图
        if (isset($ci['FacePicture'])) {
            $image = $ci['FacePicture'];
            $imageName = 'Cap_'.date('YmdHis', $data['capture_time']).'_'.date('YmdHis').mt_rand(10,99).'_'.$info['visit_count'].'.jpg';
            $imagePath = EASYSWOOLE_ROOT.$this->configPath['compare_path'].date('Ym').'/'.date("d").'/comp'.$data['device_remark'];
            $retData = Utils::saveImage($image, $imageName, $imagePath, 0);

            if ($retData['ret'] === 0) {
                $data['imgpath'] = str_replace(EASYSWOOLE_ROOT.'/webroot', '', $retData['imgSrc']);
            } else {
                $this->logger->log("设备：{$this->DeviceUUID}，保存通行记录图片失败;".$retData['ret'], LogHandel::LOG_LEVEL_INFO, 'DeviceCompareinfo');
                $this->logger->log("设备：{$this->DeviceUUID}，base64格式;".$image, LogHandel::LOG_LEVEL_INFO, 'DeviceCompareinfo');
            }
        }

        // 存储人脸背景图
        if (0) {
            if (isset($actData['Data']['CaptureInfo']['BackgroundPicture'])) {
                $image = $actData['Data']['CaptureInfo']['BackgroundPicture'];
                $imageName = 'Cap_'.date('YmdHis',$data['capture_time']).'_'.date('YmdHis').mt_rand(100,999).'_'.$info['visitcount'].'.jpg';
                $imagePath = '.'.$this->configPath['compare_path'].date('Ym').'/'.date("d").'/back'.$data['devicere_mark'];
                $imageAutoDatePath = 0;
                $retData = Utils::saveImage($image, $imageName, $imagePath, $imageAutoDatePath);

                if ($retData['ret'] === 0) {
                    $data['imgexpath'] = $retData['imgSrc'];
                }
            }
        }

        // 人脸ID
        if (isset($actData['Data']['FaceInfo']['FaceId'])) {
            $data['device_face_id'] = $actData['Data']['FaceInfo']['FaceId'];
        }

        // 人脸图片质量
        if (isset($actData['Data']['FaceInfo']['FaceQuality']) && is_numeric($actData['Data']['FaceInfoModel']['FaceQuality'])) {
            $data['face_quality'] = intval($actData['Data']['FaceInfo']['FaceQuality']);
            if ($data['face_quality'] > 10000) {
                $data['face_quality'] = $data['face_quality']*0.14655; // 85-58000
            }
        } else {
            $data['face_quality'] = 0;
        }

        // 人脸坐标
        if (isset($actData['Data']['FaceInfo']['FacePosition'])) {
            $info['face_position'] = $actData['Data']['FaceInfo']['FacePosition'];
        }

        // 比对信息
        if (isset($actData['Data']['CompareInfo'])) {
            $this->compareHandler($actData['Data']['CompareInfo'], $data, $info);
        }

        $data['create_time'] = time();
        $data['status'] = 1;

        list($year, $month, $day) = explode('-', date('Y-m-d', time()));

        $table_compare = 'sc_compare_'.$deviceInfo['school_code'].'_'.$year;
        $table_compare_info = 'sc_compare_info_'.$deviceInfo['school_code'].'_'.$year;

        if (($month == '01') && ($day == '01')) {
            $this->createTable($table_compare, $table_compare_info);
        }

        $this->compareObj->tableName($table_compare);
        $this->compareInfoObj->tableName($table_compare_info);

        $ret = $this->compareObj->add($data);
        if ($ret) {
            $info['compare_id'] = $ret;
            $info['device_mac'] = $deviceInfo['device_mac'];
            $this->compareInfoObj->add($info);
        }

        // 添加数据库失败时删除图片文件
        if (!$ret) {
            if (file_exists($retData['imgSrc'])) {
                unlink($retData['imgSrc']);
            }
            $retArray['Code'] = 0;
            $retArray['Message'] = '数据保存失败';
            $retArray['result'] = 290;

            $result['error'] = 1;
            $result['data'] = $retArray;
            return $result;
        }

        $result['data'] = [
            'data' => $data,
            'info' => $info,
            'tableName' => $table_compare,
            'tableName2' => $table_compare_info
        ];

        return $result;
    }

    // 消息推送处理
    public function pushMessage($data, $deviceInfo)
    {
        $resdata = [];
        if (isset($data['name'])) {
            $resdata['name'] = $data['name'] ? $data['name'] : '陌生人';
        } else {
            $resdata['name'] = '陌生人';
        }

        if (isset($data['faceid'])) {
            $resdata['faceid'] = $data['faceid'] ? $data['faceid'] : $data['devicefaceid'];
        } else {
            $resdata['faceid'] = $data['devicefaceid'];
        }

        $resdata['date'] = date('Y-m-d', $data['capinttime']);
        $resdata['time'] = date('H:i:s', $data['capinttime']);
        $resdata['imgpath'] = $data['imgpath'] ? $data['imgpath'] : '-';
        $resdata['mode'] = $data['mode'] ?? 0;

        if (isset($data['temper']) && !empty($data['temper'])) {
            $resdata['temper'] = $data['temper'].' ℃';
        } else {
            $resdata['temper'] = '';
        }

        $resdata['capinttime'] = $data['capinttime'];
        $resdata['faceid'] = $data['faceid'];
        $resdata['deviceid'] = $data['deviceid'];
        $resdata['imgpath'] = $data['imgpath'];
        $resdata['facequality'] = $data['facequality'];

        if (($resdata['mode'] == 1) || ($resdata['mode'] == 2) || ($resdata['mode'] == 3)) {
            $resdata['fname'] = $data['name'];
        } else {
            $resdata['fname'] = $data['devicefaceid'];
        }

        // 异步发送数据给前端
        $task = TaskManager::getInstance();
        $task->async(function () use ($resdata, $deviceInfo){
            //获取swooleServer
            $server = ServerManager::getInstance()->getSwooleServer();


            //通过公司id查询需要发送的用户，通过用户id获取fd
            $userObj = new UserModel();
            $user = $userObj->getAll('id',['companyid'=>$deviceInfo['companyid']]);

            $list = [];
            foreach ($user as $key => $value) {
                $fd = Cache::getInstance()->get('uid' . $value['id']);

                if($fd){
                    $list[] = $fd['value'];
                }
            }

            if(!empty($list)){

                //获取所有客户端id
                foreach ($list as $key => $value) {
                    $server->push($value, json_encode($resdata));
                }
            }
        });

        // 生成预警消息
        $task->async(function () use ($resdata, $deviceInfo, $ret){
            $monitorRulesObj = new MonitorRulesModel();
            $monitorLogObj = new MonitorLogModel();
            //查询是否有当前组需要进行预警
            $monitor_where['area'] = ["%,{$deviceInfo['groupid']},%",'like'];
            // $monitor_where['leaderid'] = [NULL, 'IS NOT'];
            $monitor_where['companyid'] = $deviceInfo['companyid'];
            $monitor_where['status'] = 1;
            if($resdata['mode'] == 0){
                $monitor_where['type'] = ["%4%", 'like'];
            }else{
                $monitor_where['type'] = ["%{$resdata['mode']}%", 'like'];
            }

            $monitor_field = 'id,name,type,leaderid,area,vipid,blackid,firsttime,lasttime,outtime,weeks,quality';
            $monitorGroup = $monitorRulesObj->getAll($monitor_field,$monitor_where);

            //存在预警数据
            if($monitorGroup){
                //查询当前公司的所有绑定微信的管理员，发送信息
                $userObj = new UserModel();
                $user_where = [];
                $user_where['companyid'] = $deviceInfo['companyid'];
                $user_where['status'] = 1;
                $user_where['openid'] = ['', '<>'];
                $user = $userObj->getAll('id', $user_where);

                //如果抓拍记录属于黑名单或者VIP名单则查询该人员属于哪个分组
                if(($resdata['mode'] == 1) || ($resdata['mode'] == 3) || ($resdata['mode'] == 2)){
                    $faceObj = new FaceModel();
                    $face_where = [];
                    $face_where['companyid'] = $deviceInfo['companyid'];
                    $face_where['id'] = $resdata['faceid'];
                    $depdata = $faceObj->getOne('departmentid', $face_where);
                }

                //批量插入的数据
                $insertData = [];
                foreach ($monitorGroup as $key => $value) {
                    $week = date('w', time());
                    if($week == 0){
                        $week = 7;
                    }
                    $date = date('Y-m-d', time());
                    $firsttime = strtotime($date.' '.$value['firsttime']);
                    $lasttime = strtotime($date.' '.$value['lasttime']);
                    //判断初始时间是否大于结束时间
                    if($firsttime > $lasttime){
                        //结束时间为第二天数据
                        $lasttime = strtotime('+1 day',$lasttime);
                    }

                    //判断数据是否符合发送预警标准，符合则生成发送数据
                    $inWeek = explode(',', $value['weeks']);
                    if(in_array($week, $inWeek)){

                        //判断时间是否符合预警
                        if(($resdata['capinttime'] >= $firsttime) && ($resdata['capinttime'] <= $lasttime)){
                            $data = [];
                            $data['userid'] = $deviceInfo['userid'];
                            $data['companyid'] = $deviceInfo['companyid'];
                            $data['rulesid'] = $value['id'];
                            $data['createtime'] = time();
                            $data['updatetime'] = time();
                            $data['status'] = 2;
                            $data['capinttime'] = $resdata['capinttime'];
                            $data['deviceremark'] = $deviceInfo['deviceremark'];
                            $data['imgpath'] = $resdata['imgpath'];
                            $data['fname'] = $resdata['fname'];
                            $data['faceid'] = $resdata['faceid'];

                            if(($resdata['mode'] == 1)){
                                $blackArr = explode(',', trim($value['blackid'], ','));
                                //判断该人员是否在预警黑名单分组中
                                if(in_array($depdata['departmentid'], $blackArr)){
                                    //生成数据
                                    $data['mode'] = 1;
                                }else{
                                    continue;
                                }
                            }elseif($resdata['mode'] == 3){
                                $vipArr = explode(',', trim($value['vipid'], ','));
                                //判断该人员是否在预警VIP名单分组中
                                if(in_array($depdata['departmentid'], $vipArr)){
                                    //生成数据
                                    $data['mode'] = 3;
                                }else{
                                    continue;
                                }

                            }elseif($resdata['mode'] == 0){
                                //判断质量分数是否符合标准
                                $data['mode'] = 4;
                            }else{
                                //白名单预警
                                $data['mode'] = 2;
                            }
                            //如果是陌生人，判断图片质量分数是否符合要求
                            // 	if(($resdata['facequality']  < $value['quality']) && ($data['mode'] == 4)){
                            // 	continue;
                            // }

                            $outtime = time() - ($value['outtime']*60);

                            //查询在去重的时间内是否有生成预警
                            $isset_where = [];
                            $isset_where['rulesid'] = $data['rulesid'];
                            $isset_where['mode'] = $data['mode'];
                            $isset_where['faceid'] = $data['faceid'];
                            $isset_where['deviceremark'] = $data['deviceremark'];
                            $isset_where['createtime'] = [$outtime, '>='];
                            $isset_where['companyid'] = $data['companyid'];
                            $isset = $monitorLogObj->getOne('id', $isset_where);

                            if($isset){
                                //在去重时间内已经生成报警记录，无需生成
                                continue;
                            }

                            if(isset($depdata['departmentid'])){
                                $data['departmentid'] = $depdata['departmentid'];
                            }else{
                                $data['departmentid'] = -1;
                            }

                            $sendPeople = explode(',', trim($value['leaderid'],','));


                            if(is_array($sendPeople) && (count($sendPeople) > 0)){
                                foreach ($sendPeople as $skey => $svalue) {
                                    if($svalue){
                                        $data['leaderid'] = $svalue;
                                        $data['type'] = 2;
                                        $insertData[] = $data;
                                    }
                                }
                            }

                            if(is_array($user) && (count($user) > 0)){
                                foreach ($user as $ukey => $uvalue) {
                                    if(isset($uvalue['id']) && !empty($uvalue['id'])){
                                        $data['leaderid'] = $uvalue['id'];
                                        $data['type'] = 1;
                                        $insertData[] = $data;
                                    }
                                }
                            }
                        }
                    }
                }

                //将数据批量插入数据库中
                if(count($insertData) > 0){
                    $monitorLogObj = new MonitorLogModel();

                    $resultLog = $monitorLogObj->insertMulti($insertData);

                    if($resultLog){

                        //查询所有的考勤分组
                        $deviceObj = new DeviceModel();
                        $monitorLogObj = new MonitorLogModel();
                        $monitorRulesObj = new MonitorRulesModel();
                        $date = date('Y-m-d',time());
                        $firsttime = strtotime($date.' 00:00:00');
                        $lasttime = strtotime($date.' 23:59:59');
                        //status -1发送失败，1-待发送，2-正在发送，3-发送成功；
                        $where = [];
                        $where['A.type'] = 1;
                        $where['A.id'] = [$resultLog, 'IN'];
                        $where['A.companyid'] = $deviceInfo['companyid'];
                        $where['B.status'] = 1;
                        $fields = 'A.*,B.openid,B.username,B.status as fstatus,C.name as Dname,D.token,D.api_url,D.notify_url,D.wx_appid,D.wx_secret,D.unit,D.notifier,D.templed_id,D.templed_id2,D.templed_id3';
                        //查询需要发送的数据
                        $sendData = $monitorLogObj->getLogData($fields, $where);

                        //查询发送给员工的信息
                        //status -1发送失败，1-待发送，2-正在发送，3-发送成功；
                        $where_staff = [];
                        $where_staff['A.type'] = 2;
                        $where_staff['A.id'] = [$resultLog, 'IN'];
                        $where_staff['B.status'] = 1;
                        $fields_staff = 'A.*,B.openid,B.name,B.status as fstatus,C.name as Dname,D.token,D.api_url,D.notify_url,D.wx_appid,D.wx_secret,D.unit,D.notifier,D.templed_id,D.templed_id2,D.templed_id3';
                        //查询需要发送的数据
                        $sendData2 = $monitorLogObj->getLogStaff($fields_staff, $where_staff);
                        $basePath = \Yaconf::get('basebt');
                        if(is_array($sendData) && !empty($sendData)){
                            $wxConfigObj = new WxConfigModel();
                            $wxConfig = $wxConfigObj->getOne('token,api_url,notify_url,wx_appid,wx_secret,unit,notifier,templed_id,templed_id2,templed_id3',['id'=>1]);
                            //发送管理员预警信息
                            foreach ($sendData as $key => $value) {
                                if($value['fstatus'] != 1){
                                    //将该条信息status变为4
                                    $monitorLogObj->update(['status'=>4], ['id'=>$value['id']]);
                                    //该员工已解绑，或者被拉入黑名单
                                    continue;
                                }
                                $data = [];
                                if(!empty($value['openid'])){
                                    $data['openid'] = $value['openid'];
                                }else{
                                    //将该条信息status变为4
                                    $monitorLogObj->update(['status'=>4], ['id'=>$value['id']]);
                                    //该员工已解绑
                                    continue;
                                }

                                $data['templed_id'] = $value['templed_id'] ? $value['templed_id'] : $wxConfig['templed_id'];
                                $data['wx_appid'] = $value['wx_appid'] ? $value['wx_appid'] : $wxConfig['wx_appid'];
                                $data['wx_secret'] = $value['wx_secret'] ? $value['wx_secret'] : $wxConfig['wx_secret'];
                                $data['devicename'] = $value['Dname'];
                                //默认信息以防报错
                                $data['type'] = '陌生人预警';
                                $data['first'] = "您好，您有一条陌生人预警信息";
                                $data['remark'] = "陌生人，进入{$value['Dname']}区域，请知晓";
                                if($value['mode'] == 1){
                                    //黑名单预警
                                    $data['type'] = '黑名单报警';
                                    $data['first'] = "您好，您有一条黑名单报警信息";
                                    $data['remark'] = "黑名单：{$value['fname']}，非法闯入{$value['Dname']}区域，请知晓";
                                }elseif($value['mode'] == 2){
                                    $data['type'] = '白名单预警';
                                    $data['first'] = "您好，您有一条白名单预警信息";
                                    $data['remark'] = "白名单：{$value['fname']}，进入{$value['Dname']}区域，请知晓";
                                }elseif($value['mode'] == 2){
                                    $data['type'] = 'VIP提醒';
                                    $data['first'] = "您好，您有一条VIP名单提醒信息";
                                    $data['remark'] = "VIP：{$value['fname']}，已进入{$value['Dname']}区域，请进行迎接";
                                }elseif($value['mode'] == 4){
                                    $data['type'] = '陌生人预警';
                                    $data['first'] = "您好，您有一条陌生人预警信息";
                                    $data['remark'] = "陌生人，进入{$value['Dname']}区域，请知晓";
                                }
                                $data['area'] = $value['Dname'];
                                $data['token'] = $value['token'] ? $value['token'] : $wxConfig['token'];
                                $data['id'] = $value['id'];
                                $data['api_url'] = $value['api_url'] ? $value['api_url'] : $wxConfig['api_url'];
                                $data['sendnum'] = $value['sendnum'];

                                $postdata = [
                                    'touser' => $data['openid'], //接收者openid , 必须
                                    'template_id'=> $data['templed_id'], //模板ID, 必须
                                    'url'=> ($basePath['wxPath'].'details?ids='. $data['id']), //模板跳转链接（海外帐号没有跳转能力） , 非必须
                                    'data'=>[ //消息数据,必须,数组里键名不能变,键值自由组装
                                        'first'=>['value'=> $data['first'] , 'color'=>'#173177'], //您有一条预警信息
                                        'keyword1'=>['value'=>$data['devicename'],'color'=>'#173177'],  //学校 (必须)
                                        'keyword2'=>['value'=>date('Y-m-d H:i:s'),'color'=>'#173177'],    //地点 (必须)
                                        'keyword3'=>['value'=>$data['type'],'color'=>'#173177'],  //预警类型 (必须)
                                        'keyword4'=>['value'=>$data['area'],'color'=>'#173177'],  //预警防区 (必须)
                                        'remark'=>['value'=>$data['remark'],'color'=>'#000'] //备注
                                    ]
                                ];
                                if($basePath['type'] == 'cloud'){
                                    $result = WeChat::pushmsg($postdata, $data['wx_appid'], $data['wx_secret']);

                                    $monitorLogObj = new MonitorLogModel();

                                    $up_data = [];
                                    $up_data['sendnum'] = $data['sendnum'] + 1;
                                    $up_data['response'] = $result;
                                    $up_where = [];
                                    $up_where['id'] = $data['id'];
                                    if($result == 'ok'){
                                        //推送成功，更新数据
                                        $up_data['updatetime'] = time();
                                        $up_data['status'] = 3;
                                    }else{
                                        //失败更新数据
                                        $up_data['failtime'] = time();
                                        $up_data['status'] = -1;
                                    }
                                    $monitorLogObj->update($up_data, $up_where);
                                }else{
                                    $sendurl = $value['api_url'].$basePath['wxpushPath'];
                                    $sdata = [];
                                    $sdata['sole'] = $value['token'];
                                    $sdata['info'] = $postdata;
                                    $sdata['timestamp'] = time();
                                    $sdata['sign'] = Utils::makeSignWechat($sdata, $value['token']);
                                    $sendData = json_encode($sdata);
                                    $head = [];
                                    $head['Content-Type'] = 'application/json;charset=utf-8';
                                    $curlObj = new Curl();
                                    $result = $curlObj->request('POST', $sendurl, $sendData, $head);
                                    $monitorLogObj = new MonitorLogModel();
                                    $up_data = [];
                                    $up_data['sendnum'] = $data['sendnum'] + 1;
                                    $up_data['response'] = $result;
                                    $up_where = [];
                                    $up_where['id'] = $data['id'];
                                    $json_result = json_decode($result, true);
                                    if(isset($json_result['code']) && ($json_result['code'] == 1)){
                                        //推送成功，更新数据
                                        $up_data['updatetime'] = time();
                                        $up_data['status'] = 3;
                                    } else {
                                        //失败更新数据
                                        $up_data['failtime'] = time();
                                        $up_data['status'] = -1;
                                    }
                                    $monitorLogObj->update($up_data, $up_where);
                                }
                            }
                        }


                        if(is_array($sendData2) && !empty($sendData2)){

                            //发送给员工预警信息
                            foreach ($sendData2 as $key => $value) {
                                if($value['fstatus'] != 1){
                                    //将该条信息status变为4
                                    $monitorLogObj->update(['status'=>4], ['id'=>$value['id']]);
                                    //该员工已解绑，或者被拉入黑名单
                                    continue;
                                }
                                $data = [];
                                if(!empty($value['openid'])){
                                    $data['openid'] = $value['openid'];
                                }else{
                                    //将该条信息status变为4
                                    $monitorLogObj->update(['status'=>4], ['id'=>$value['id']]);
                                    //该员工已解绑
                                    continue;
                                }

                                $data['templed_id'] = $value['templed_id'] ? $value['templed_id'] : $wxConfig['templed_id'];
                                $data['wx_appid'] = $value['wx_appid'] ? $value['wx_appid'] : $wxConfig['wx_appid'];
                                $data['wx_secret'] = $value['wx_secret'] ? $value['wx_secret'] : $wxConfig['wx_secret'];
                                $data['devicename'] = $value['Dname'];
                                $data['type'] = '陌生人预警';
                                $data['first'] = "您好，您有一条陌生人预警信息";
                                $data['remark'] = "陌生人，进入{$value['Dname']}区域，请知晓";
                                if($value['mode'] == 1){
                                    //黑名单预警
                                    $data['type'] = '黑名单报警';
                                    $data['first'] = "您好，您有一条黑名单报警信息";
                                    $data['remark'] = "黑名单：{$value['fname']}，非法闯入{$value['Dname']}区域，请知晓";
                                }elseif($value['mode'] == 2){
                                    $data['type'] = '白名单预警';
                                    $data['first'] = "您好，您有一条白名单预警信息";
                                    $data['remark'] = "白名单：{$value['fname']}，进入{$value['Dname']}区域，请知晓";
                                }elseif($value['mode'] == 2){
                                    $data['type'] = 'VIP提醒';
                                    $data['first'] = "您好，您有一条VIP名单提醒信息";
                                    $data['remark'] = "VIP：{$value['fname']}，已进入{$value['Dname']}区域，请进行迎接";
                                }elseif($value['mode'] == 4){
                                    $data['type'] = '陌生人预警';
                                    $data['first'] = "您好，您有一条陌生人预警信息";
                                    $data['remark'] = "陌生人，进入{$value['Dname']}区域，请知晓";
                                }
                                $data['area'] = $value['Dname'];
                                $data['token'] = $value['token'] ? $value['token'] : $wxConfig['token'];
                                $data['id'] = $value['id'];
                                $data['api_url'] = $value['api_url'] ? $value['api_url'] : $wxConfig['api_url'];
                                $data['sendnum'] = $value['sendnum'];

                                $postdata = [
                                    'touser' => $data['openid'], //接收者openid , 必须
                                    'template_id'=> $data['templed_id'], //模板ID, 必须
                                    'url'=> ($basePath['wxPath'].'details?ids='. $data['id']), //模板跳转链接（海外帐号没有跳转能力） , 非必须
                                    'data'=>[ //消息数据,必须,数组里键名不能变,键值自由组装
                                        'first'=>['value'=> $data['first'] , 'color'=>'#173177'], //您有一条预警信息
                                        'keyword1'=>['value'=>$data['devicename'],'color'=>'#173177'],  //学校 (必须)
                                        'keyword2'=>['value'=>date('Y-m-d H:i:s'),'color'=>'#173177'],    //地点 (必须)
                                        'keyword3'=>['value'=>$data['type'],'color'=>'#173177'],  //预警类型 (必须)
                                        'keyword4'=>['value'=>$data['area'],'color'=>'#173177'],  //预警防区 (必须)
                                        'remark'=>['value'=>$data['remark'],'color'=>'#000'] //备注
                                    ]
                                ];
                                if($basePath['type'] == 'cloud'){
                                    $result = WeChat::pushmsg($postdata, $data['wx_appid'], $data['wx_secret']);

                                    $monitorLogObj = new MonitorLogModel();

                                    $up_data = [];
                                    $up_data['sendnum'] = $data['sendnum'] + 1;
                                    $up_data['response'] = $result;
                                    $up_where = [];
                                    $up_where['id'] = $data['id'];
                                    if($result == 'ok'){
                                        //推送成功，更新数据
                                        $up_data['updatetime'] = time();
                                        $up_data['status'] = 3;
                                    }else{
                                        //失败更新数据
                                        $up_data['failtime'] = time();
                                        $up_data['status'] = -1;
                                    }
                                    $monitorLogObj->update($up_data, $up_where);
                                }else{
                                    $sendurl = $value['api_url'].$basePath['wxpushPath'];
                                    $sdata = [];
                                    $sdata['sole'] = $value['token'];
                                    $sdata['info'] = $postdata;
                                    $sdata['timestamp'] = time();
                                    $sdata['sign'] = Utils::makeSignWechat($sdata, $value['token']);
                                    $sendData = json_encode($sdata);
                                    $head = [];
                                    $head['Content-Type'] = 'application/json;charset=utf-8';
                                    $curlObj = new Curl();
                                    $result = $curlObj->request('POST', $sendurl, $sendData, $head);
                                    $monitorLogObj = new MonitorLogModel();
                                    $up_data = [];
                                    $up_data['sendnum'] = $data['sendnum'] + 1;
                                    $up_data['response'] = $result;
                                    $up_where = [];
                                    $up_where['id'] = $data['id'];
                                    $json_result = json_decode($result, true);
                                    if(isset($json_result['code']) && ($json_result['code'] == 1)){
                                        //推送成功，更新数据
                                        $up_data['updatetime'] = time();
                                        $up_data['status'] = 3;
                                    } else {
                                        //失败更新数据
                                        $up_data['failtime'] = time();
                                        $up_data['status'] = -1;
                                    }
                                    $monitorLogObj->update($up_data, $up_where);
                                }

                            }
                        }

                    }

                }
            }

        });

        // 体温预警消息
        if (!empty($data['temper'])) {
            //发送体温异常报警信息
            $task->async(function () use ($resdata, $deviceInfo, $ret) {
                //查询当前公司体温报警标准
                $temperObj = new TemperRulesModel();
                $rules_where = [];
                $rules_where['companyid'] = $deviceInfo['companyid'];
                $rules_where['status'] = 1;
                $rules = $temperObj->getOne('id,temper,leaderid', $rules_where);
                if ($rules) {
                    //存在规则
                    if ($resdata['temper'] >= $rules['temper']) {
                        //体温异常，进行报警
                        //查询当前公司的所有绑定微信的管理员，发送信息
                        $userObj = new UserModel();
                        $user_where = [];
                        $user_where['companyid'] = $deviceInfo['companyid'];
                        $user_where['status'] = 1;
                        $user_where['openid'] = ['', '<>'];
                        $user = $userObj->getAll('id', $user_where);
                        $sendPeople = explode(',', trim($rules['leaderid'], ','));
                        //批量插入的数据
                        $insertData = [];

                        $data = [];
                        $data['userid'] = $deviceInfo['userid'];
                        $data['parentid'] = $deviceInfo['parentid'];
                        $data['parentpath'] = $deviceInfo['parentpath'];
                        $data['companyid'] = $deviceInfo['companyid'];
                        $data['createtime'] = time();
                        $data['updatetime'] = time();
                        $data['status'] = 2;
                        $data['temper'] = $resdata['temper'];
                        $data['capinttime'] = $resdata['capinttime'];
                        $data['deviceremark'] = $deviceInfo['deviceremark'];
                        $data['imgpath'] = $resdata['imgpath'];
                        $data['fname'] = $resdata['fname'];
                        $data['faceid'] = $resdata['faceid'];
                        if ($resdata['mode'] == 0) {
                            $data['mode'] = 4;
                        } else {
                            $data['mode'] = $resdata['mode'];
                        }

                        if (is_array($user) && (count($user) > 0)) {
                            foreach ($user as $key => $value) {
                                if (isset($value['id']) && !empty($value['id'])) {
                                    $data['leaderid'] = $value['id'];
                                    $data['type'] = 1;
                                    $insertData[] = $data;
                                }
                            }
                        }

                        if (is_array($sendPeople) && (count($sendPeople) > 0)) {
                            foreach ($sendPeople as $key => $value) {
                                if (!empty($value)) {
                                    $data['leaderid'] = $value;
                                    $data['type'] = 2;
                                    $insertData[] = $data;
                                }
                            }
                        }
                        //将数据批量插入数据库中
                        if (count($insertData) > 0) {
                            $temperLogObj = new TemperLogModel();
                            $temperLog = $temperLogObj->insertMulti($insertData);
                            if ($temperLog) {
                                $temperLogObj = new TemperLogModel();
                                $date = date('Y-m-d', time());
                                //status -1发送失败，1-待发送，2-正在发送，3-发送成功；
                                $where = [];
                                $where['A.type'] = 1;
                                $where['A.id'] = [$temperLog, 'IN'];
                                $where['A.companyid'] = $deviceInfo['companyid'];
                                $where['B.status'] = 1;
                                $fields = 'A.*,B.openid,B.username,B.status as fstatus,C.name as Dname,D.token,D.api_url,D.notify_url,D.wx_appid,D.wx_secret,D.unit,D.notifier,D.templed_id,D.templed_id2,D.templed_id3';
                                //查询需要发送的数据
                                $sendData = $temperLogObj->getLogData($fields, $where);
                                //查询发送给员工的信息
                                //status -1发送失败，1-待发送，2-正在发送，3-发送成功；
                                $where_staff = [];
                                $where_staff['A.type'] = 2;
                                $where_staff['A.id'] = [$temperLog, 'IN'];
                                $where_staff['B.status'] = 1;
                                $fields_staff = 'A.*,B.openid,B.name,B.status as fstatus,C.name as Dname,D.token,D.api_url,D.notify_url,D.wx_appid,D.wx_secret,D.unit,D.notifier,D.templed_id,D.templed_id2,D.templed_id3';
                                //查询需要发送的数据
                                $sendData2 = $temperLogObj->getLogStaff($fields_staff, $where_staff);
                                $basePath = \Yaconf::get('basebt');
                                if (is_array($sendData) && !empty($sendData)) {
                                    $wxConfigObj = new WxConfigModel();
                                    $wxConfig = $wxConfigObj->getOne('token,api_url,notify_url,wx_appid,wx_secret,unit,notifier,templed_waring,templed_id,templed_id2,templed_id3', ['id' => 1]);
                                    //发送管理员预警信息
                                    foreach ($sendData as $key => $value) {
                                        if ($value['fstatus'] != 1) {
                                            //该员工已解绑，或者被拉入黑名单
                                            continue;
                                        }
                                        $data = [];
                                        if (!empty($value['openid'])) {
                                            $data['openid'] = $value['openid'];
                                        } else {
                                            //该员工已解绑
                                            continue;
                                        }

                                        $data['templed_waring'] = $value['templed_waring'] ? $value['templed_waring'] : $wxConfig['templed_waring'];
                                        $data['wx_appid'] = $value['wx_appid'] ? $value['wx_appid'] : $wxConfig['wx_appid'];
                                        $data['wx_secret'] = $value['wx_secret'] ? $value['wx_secret'] : $wxConfig['wx_secret'];
                                        $data['devicename'] = $value['Dname'];
                                        $data['type'] = '体温异常报警';
                                        $data['first'] = "您好，有人体温异常，请及时查看";
                                        $data['remark'] = "{$value['fname']}，在{$value['Dname']}区域发现体温{$value['temper']}度，请知晓";
                                        $data['area'] = $value['Dname'];
                                        $data['id'] = $value['id'];
                                        $data['api_url'] = $value['api_url'] ? $value['api_url'] : $wxConfig['api_url'];
                                        $data['sendnum'] = $value['sendnum'];

                                        $postdata = [
                                            'touser' => $data['openid'], //接收者openid , 必须
                                            'template_id' => $data['templed_waring'], //模板ID, 必须
                                            'url' => ($basePath['wxPath'].'temper/detail?ids='. $data['id']), //模板跳转链接（海外帐号没有跳转能力） , 非必须
                                            'data' => [ //消息数据,必须,数组里键名不能变,键值自由组装
                                                'first' => ['value' => $data['first'], 'color' => '#173177'], //您有一条预警信息
                                                'keyword1' => ['value' => $value['fname'], 'color' => '#173177'],  //学校 (必须)
                                                'keyword2' => ['value' => date('Y-m-d H:i:s'), 'color' => '#173177'],    //地点 (必须)
                                                'keyword3' => ['value' => $data['type'], 'color' => '#173177'],  //预警类型 (必须)
                                                'keyword4' => ['value' => $data['area'], 'color' => '#173177'],  //预警防区 (必须)
                                                'remark' => ['value' => $data['remark'], 'color' => '#000'] //备注
                                            ]
                                        ];
                                        if($basePath['type'] == 'cloud'){
                                            $result = WeChat::pushmsg($postdata, $data['wx_appid'], $data['wx_secret']);

                                            $temperLogObj = new TemperLogModel();

                                            $up_data = [];
                                            $up_data['sendnum'] = $data['sendnum'] + 1;
                                            $up_data['response'] = $result;
                                            $up_where = [];
                                            $up_where['id'] = $data['id'];
                                            if ($result == 'ok') {
                                                //推送成功，更新数据
                                                $up_data['updatetime'] = time();
                                                $up_data['status'] = 3;
                                            } else {
                                                //失败更新数据
                                                $up_data['failtime'] = time();
                                                $up_data['status'] = -1;
                                            }
                                            $temperLogObj->update($up_data, $up_where);
                                        }else{
                                            $sendurl = $value['api_url'].$basePath['wxpushPath'];
                                            $sdata = [];
                                            $sdata['sole'] = $value['token'];
                                            $sdata['info'] = $postdata;
                                            $sdata['timestamp'] = time();
                                            $sdata['sign'] = Utils::makeSignWechat($sdata, $value['token']);
                                            $sendData = json_encode($sdata);
                                            $head = [];
                                            $head['Content-Type'] = 'application/json;charset=utf-8';
                                            $curlObj = new Curl();
                                            $result = $curlObj->request('POST', $sendurl, $sendData, $head);
                                            $temperLogObj = new TemperLogModel();
                                            $up_data = [];
                                            $up_data['sendnum'] = $data['sendnum'] + 1;
                                            $up_data['response'] = $result;
                                            $up_where = [];
                                            $up_where['id'] = $data['id'];
                                            $json_result = json_decode($result, true);
                                            if(isset($json_result['code']) && ($json_result['code'] == 1)){
                                                //推送成功，更新数据
                                                $up_data['updatetime'] = time();
                                                $up_data['status'] = 3;
                                            } else {
                                                //失败更新数据
                                                $up_data['failtime'] = time();
                                                $up_data['status'] = -1;
                                            }
                                            $temperLogObj->update($up_data, $up_where);
                                        }
                                    }
                                }


                                if (is_array($sendData2) && !empty($sendData2)) {

                                    //发送给员工预警信息
                                    foreach ($sendData2 as $key => $value) {
                                        if ($value['fstatus'] != 1) {
                                            //该员工已解绑，或者被拉入黑名单
                                            continue;
                                        }
                                        $data = [];
                                        if (!empty($value['openid'])) {
                                            $data['openid'] = $value['openid'];
                                        } else {
                                            //该员工已解绑
                                            continue;
                                        }

                                        $data['templed_waring'] = $value['templed_waring'] ? $value['templed_waring'] : $wxConfig['templed_waring'];
                                        $data['wx_appid'] = $value['wx_appid'] ? $value['wx_appid'] : $wxConfig['wx_appid'];
                                        $data['wx_secret'] = $value['wx_secret'] ? $value['wx_secret'] : $wxConfig['wx_secret'];
                                        $data['devicename'] = $value['Dname'];
                                        $data['type'] = '体温异常报警';
                                        $data['first'] = "您好，有人体温异常，请及时查看";
                                        $data['remark'] = "{$value['fname']}，在{$value['Dname']}区域发现体温{$value['temper']}度，请知晓";
                                        $data['area'] = $value['Dname'];
                                        $data['id'] = $value['id'];
                                        $data['api_url'] = $value['api_url'] ? $value['api_url'] : $wxConfig['api_url'];
                                        $data['sendnum'] = $value['sendnum'];

                                        $postdata = [
                                            'touser' => $data['openid'], //接收者openid , 必须
                                            'template_id' => $data['templed_waring'], //模板ID, 必须
                                            'url' => ($basePath['wxPath'].'temper/detail?ids='. $data['id']), //模板跳转链接（海外帐号没有跳转能力） , 非必须
                                            'data' => [ //消息数据,必须,数组里键名不能变,键值自由组装
                                                'first' => ['value' => $data['first'], 'color' => '#173177'], //您有一条预警信息
                                                'keyword1' => ['value' => $value['fname'], 'color' => '#173177'],  //学校 (必须)
                                                'keyword2' => ['value' => date('Y-m-d H:i:s'), 'color' => '#173177'],    //地点 (必须)
                                                'keyword3' => ['value' => $data['type'], 'color' => '#173177'],  //预警类型 (必须)
                                                'keyword4' => ['value' => $data['area'], 'color' => '#173177'],  //预警防区 (必须)
                                                'remark' => ['value' => $data['remark'], 'color' => '#000'] //备注
                                            ]
                                        ];
                                        if($basePath['type'] == 'cloud'){
                                            $result = WeChat::pushmsg($postdata, $data['wx_appid'], $data['wx_secret']);
                                            $temperLogObj = new TemperLogModel();
                                            $up_data = [];
                                            $up_data['sendnum'] = $data['sendnum'] + 1;
                                            $up_data['response'] = $result;
                                            $up_where = [];
                                            $up_where['id'] = $data['id'];
                                            if ($result == 'ok') {
                                                //推送成功，更新数据
                                                $up_data['updatetime'] = time();
                                                $up_data['status'] = 3;
                                            } else {
                                                //失败更新数据
                                                $up_data['failtime'] = time();
                                                $up_data['status'] = -1;
                                            }
                                            $temperLogObj->update($up_data, $up_where);
                                        }else{
                                            $sendurl = $value['api_url'].$basePath['wxpushPath'];
                                            $sdata = [];
                                            $sdata['sole'] = $value['token'];
                                            $sdata['info'] = $postdata;
                                            $sdata['timestamp'] = time();
                                            $sdata['sign'] = Utils::makeSignWechat($sdata, $value['token']);
                                            $sendData = json_encode($sdata);
                                            $head = [];
                                            $head['Content-Type'] = 'application/json;charset=utf-8';
                                            $curlObj = new Curl();
                                            $result = $curlObj->request('POST', $sendurl, $sendData, $head);
                                            $temperLogObj = new TemperLogModel();
                                            $up_data = [];
                                            $up_data['sendnum'] = $data['sendnum'] + 1;
                                            $up_data['response'] = $result;
                                            $up_where = [];
                                            $up_where['id'] = $data['id'];
                                            $json_result = json_decode($result, true);
                                            if(isset($json_result['code']) && ($json_result['code'] == 1)){
                                                //推送成功，更新数据
                                                $up_data['updatetime'] = time();
                                                $up_data['status'] = 3;
                                            } else {
                                                //失败更新数据
                                                $up_data['failtime'] = time();
                                                $up_data['status'] = -1;
                                            }
                                            $temperLogObj->update($up_data, $up_where);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }

        // 个人考勤推送消息
        if ($resdata['mode'] == 2){
            //查看是否需要生成考勤信息发送记录
            //发送体温异常报警信息
            $task->async(function () use($resdata, $deviceInfo, $ret){
                //1、查询当前公司考勤分组
                //2、判断当前设备是否在考勤分组中
                //3、查询当前人员所属分组
                //4、判断该员工是否考勤
                //5、判断当天是否需要考勤
                //6、判断当前时间段是否需要发送考勤信息，是否已经发送，若没发送则发送
                $attendGroupObj = new AttendGroupModel();
                $attend_where = [];
                $attend_where['status'] = 1;
                $attend_where['companyid'] = $deviceInfo['companyid'];
                $attendGroupData = $attendGroupObj->getAll('id,groupid,departmentid,faceid,week,classid,type', $attend_where);

                //查询当前考勤人员信息
                $faceObj = new FaceModel();
                $staff_field = 'id,userid,parentid,parentpath,companyid,name,numbers,departmentid,status,openid,push_type';
                $staff_where = [];
                $staff_where['status'] = 1;
                $staff_where['mode'] = 2;
                $staff_where['companyid'] = $deviceInfo['companyid'];
                $staff_where['id'] = $resdata['faceid'];
                $staff = $faceObj->getOne($staff_field, $staff_where);
                if($attendGroupData){
                    $attendGroup = [];
                    //循环判断是有符合此人的考勤分组
                    foreach($attendGroupData as $key=>$value){
                        $groupidArr = explode(',', trim($value['groupid'], ','));
                        $depArr = explode(',', trim($value['departmentid'], ','));
                        $staffidArr = explode(',', trim($value['faceid'], ','));
                        $staffDepArr = explode(',', $staff['departmentid']);
                        $staffArr = array_intersect($staffDepArr, $depArr);
                        //判断设备是否在考勤组，该人是否在考勤部门，该人是否需要考勤，该人是否有openid
                        if(in_array($deviceInfo['groupid'], $groupidArr) && $staffArr && !in_array($staff['id'], $staffidArr) && !empty($staff['openid'])){
                            $attendGroup = $value;
                        }
                    }
                    //存在符合此人的考勤分组
                    if(count($attendGroup) <= 0){
                        return ;
                    }
                    list($year, $month, $day) = explode('-', date('Y-m-d'));
                    //判断当天是否需要考勤
                    //查询当前考勤分组的日历，或者排班日期
                    $classid = 0;
                    $nowDate = date('Y-m-d', time());
                    //当天初始时间，结束时间
                    $lingInt = strtotime($nowDate.' 00:00:00');
                    $eventInt = strtotime($nowDate.' 23:59:59');
                    //if(($resdata['capinttime'] < $lingInt) || ($resdata['capinttime'] > $eventInt)){
                    //    return;
                    //}
                    if($attendGroup['type'] == 1){
                        //考勤日历
                        $w = date('w', time());
                        $weekArr = explode(',', trim($attendGroup['week'], ','));
                        $classArr = explode(',', trim($attendGroup['classid'], ','));
                        //查询日历
                        $calendarObj = new CalendarModel();
                        $calendar_where = [];
                        $calendar_where['time'] = $lingInt;
                        $calendar_where['status'] = 1;
                        $calendar_where['attendid'] = $attendGroup['id'];
                        $calendar = $calendarObj->getOne('id,rest', $calendar_where);

                        if((isset($calendar['rest']) && ($calendar['rest'] == 1)) || (!$calendar && in_array($w,$weekArr))){
                            //特殊需要上班,和不存在日历，正常需要上班
                            //获取班次id
                            foreach($classArr as $ckey=>$cvalue){
                                $classWeek = explode('-', $cvalue);
                                if($w == reset($classWeek)){
                                    $classid = end($classWeek);
                                }
                            }
                            //班次不存在，获取第一天需要上班作为班次
                            if($classid == 0){
                                $Monday = reset($classArr);
                                $classWeek = explode('-', $Monday);
                                $classid = end($classWeek);
                            }
                        }
                    }else{
                        //排班日历
                        $scheduleObj = new ScheduleModel();
                        $schedule_field = 'id, schedule';
                        $schedule_where = [];
                        $schedule_where['attendid'] = $attendGroup['id'];
                        $schedule_where['faceid'] = $staff['id'];
                        $schedule_where['year'] = $year;
                        $schedule_where['month'] = $month;
                        $schedule = $scheduleObj->getOne($schedule_field, $schedule_where);
                        if($schedule){
                            //查看当前是否需要上班
                            $scheduleDetail = json_decode($schedule['schedule'], true);
                            foreach($scheduleDetail as $key=>$value){
                                if($key == $day){
                                    //获取当天班次
                                    $classid = $value;
                                }
                            }
                        }
                    }
                    if($classid != 0){
                        //需要上班，查询对应的班次
                        $classObj = new ClassesModel();
                        $class_field = 'id,name,type,first,second,three,four,five,six,flex,late,early,moring,after';
                        $classes = $classObj->getOne($class_field, ['id'=>$classid]);
                        if($classes){
                            //查询是否已经发送过打卡数据
                            $attendSendObj = new AttendSendModel();
                            $send_where = [];
                            $send_where['groupid'] = $attendGroup['id'];
                            $send_where['faceid'] = $staff['id'];
                            $send_where['createtime'] = [[$lingInt, $eventInt], 'BETWEEN'];
                            $send_where['type'] = 1;
                            //需要发送的数据和插入的数据
                            $data = [];
                            //在判断里进行查询是否已经发送过数据
                            $isSend = false;
                            if($classes['type'] == 1){
                                //一天两次考勤
                                $firstInt = strtotime($nowDate.' '.$classes['first']);
                                $secondInt = strtotime($nowDate.' '.$classes['second']) - $classes['early']*60;
                                $threeInt = strtotime($nowDate.' '.$classes['three']);
                                $fourInt = strtotime($nowDate.' '.$classes['four']);

                                if(($resdata['capinttime'] < $firstInt) && ($resdata['capinttime'] >= $lingInt)){
                                    //第一次上班正常打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 1;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 1;

                                }elseif(($resdata['capinttime'] > $firstInt) && ($resdata['capinttime'] <= $threeInt)){
                                    //迟到打卡，判断是否存在正常打卡或者迟到打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 1;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 1;
                                }elseif(($resdata['capinttime'] >= $secondInt) && ($resdata['capinttime'] <= $eventInt)){
                                    //正常下班打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 2;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 2;
                                }
                            }elseif($classes['type'] == 2){
                                //一天四次考勤
                                $firstInt = strtotime($nowDate.' '.$classes['first']);
                                $secondInt = strtotime($nowDate.' '.$classes['second']) - $classes['early']*60;
                                $threeInt = strtotime($nowDate.' '.$classes['three']);
                                $fourInt = strtotime($nowDate.' '.$classes['four']) - $classes['early']*60;

                                if(($resdata['capinttime'] < $firstInt) && ($resdata['capinttime'] >= $lingInt)){
                                    //第一次上班正常打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 1;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 1;

                                }elseif(($resdata['capinttime'] > $firstInt) && ($resdata['capinttime'] <= $secondInt)){
                                    //迟到打卡，判断是否存在正常打卡或者迟到打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 1;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 1;
                                }elseif(($resdata['capinttime'] >= $secondInt) && ($resdata['capinttime'] <= $threeInt)){
                                    //中午下班打卡，或者下午上班
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 2;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $send_where['signtype'] = 2;
                                    //存在中午下班打卡
                                    if($isSend){
                                        //判断是否存在下午上班打卡
                                        $send_where['signtype'] = 3;
                                        $isSend = $attendSendObj->getOne('id', $send_where);
                                        $send_where['signtype'] = 3;
                                    }

                                }elseif(($resdata['capinttime'] >= $fourInt) && ($resdata['capinttime'] <= $eventInt)){
                                    //下午下班
                                    $send_where['signtype'] = 4;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 4;
                                }
                            }elseif($classes['type'] == 3){
                                //一天六次考勤
                                $firstInt = strtotime($nowDate.' '.$classes['first']);
                                $secondInt = strtotime($nowDate.' '.$classes['second']) - $classes['early']*60;
                                $threeInt = strtotime($nowDate.' '.$classes['three']);
                                $fourInt = strtotime($nowDate.' '.$classes['four']) - $classes['early']*60;
                                $fiveInt = strtotime($nowDate.' '.$classes['five']);
                                $sixInt = strtotime($nowDate.' '.$classes['six']) - $classes['early']*60;

                                if(($resdata['capinttime'] < $firstInt) && ($resdata['capinttime'] >= $lingInt)){
                                    //第一次上班正常打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 1;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 1;

                                }elseif(($resdata['capinttime'] > $firstInt) && ($resdata['capinttime'] <= $secondInt)){
                                    //迟到打卡，判断是否存在正常打卡或者迟到打卡
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 1;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 1;
                                }elseif(($resdata['capinttime'] >= $secondInt) && ($resdata['capinttime'] <= $threeInt)){
                                    //中午下班打卡，或者下午上班
                                    //查询是否有推送信息
                                    $send_where['signtype'] = 2;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $send_where['signtype'] = 2;
                                    //存在中午下班打卡
                                    if($isSend){
                                        //判断是否存在下午上班打卡
                                        $send_where['signtype'] = 3;
                                        $isSend = $attendSendObj->getOne('id', $send_where);
                                        $send_where['signtype'] = 3;
                                    }

                                }elseif(($resdata['capinttime'] >= $fourInt) && ($resdata['capinttime'] <= $fiveInt)){
                                    //下午下班
                                    $send_where['signtype'] = 4;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 4;
                                    if($isSend){
                                        $send_where['signtype'] = 5;
                                        $isSend = $attendSendObj->getOne('id', $send_where);
                                        $data['signtype'] = 5;
                                    }
                                }elseif(($resdata['capinttime'] >= $sixInt) && ($resdata['capinttime'] <= $eventInt)){
                                    //下午下班
                                    $send_where['signtype'] = 6;
                                    $isSend = $attendSendObj->getOne('id', $send_where);
                                    $data['signtype'] = 6;

                                }
                            }

                            if(!$isSend && isset($data['signtype'])){
                                //1-正常打卡推送，2-提醒打卡推送，3-未打卡推送
                                $data['type'] = 1;
                                $data['userid'] = $staff['userid'];
                                $data['parentid'] = $staff['parentid'];
                                $data['parentpath'] = $staff['parentpath'];
                                $data['companyid'] = $staff['companyid'];
                                $data['groupid'] = $attendGroup['id'];
                                $data['name'] = $staff['name'];
                                $data['faceid'] = $staff['id'];
                                $data['numbers'] = $staff['numbers'];
                                $data['departmentid'] = $staff['departmentid'];
                                $data['temper'] = $resdata['temper'];
                                $data['capinttime'] = $resdata['capinttime'];
                                $data['deviceremark'] = $deviceInfo['deviceremark'];
                                $data['imgpath'] = $resdata['imgpath'];
                                $data['sendnum'] = 0;
                                $data['status'] = 2;
                                $data['createtime'] = time();

                                //第一次打卡，添加发送打卡微信发送记录
                                $sendRes = $attendSendObj->add($data);
                                if($sendRes){
                                    //进行发送数据
                                    $first = "{$staff['name']}您好，您有一条考勤消息，请查收";
                                    $HourMin = date('H:i', $resdata['capinttime']);
                                    if(($data['signtype'] == 1) || ($data['signtype'] == 3) || ($data['signtype'] == 5)){
                                        $remark = "{$staff['name']}您好，您在{$HourMin}上班打卡成功，点击查看详情可查看打卡图片";
                                    }else{
                                        $remark = "{$staff['name']}您好，您在{$HourMin}下班打卡成功，点击查看详情可查看打卡图片";
                                    }
                                    $basePath = \Yaconf::get('basebt');
                                    $wxConfigObj = new WxConfigModel();
                                    $wxConfig = $wxConfigObj->getOne('id,api_url,templed_id,token,wx_appid,wx_secret', ['companyid'=>$deviceInfo['companyid']]);
                                    if($basePath['type'] == 'cloud'){
                                        $postdata = [
                                            'touser' => $staff['openid'], //接收者openid , 必须
                                            'template_id'=> $wxConfig['templed_id'], //模板ID, 必须
                                            'url'=> ($basePath['wxPath'].'attend?ids='. $sendRes.'&token='.$wxConfig['token']), //模板跳转链接（海外帐号没有跳转能力） , 非必须
                                            'data'=>[ //消息数据,必须,数组里键名不能变,键值自由组装
                                                'first'=>['value'=> $first , 'color'=>'#173177'], //您有一条预警信息
                                                'keyword1'=>['value'=>date('Y-m-d H:i', $resdata['capinttime']),'color'=>'#173177'],  //学校 (必须)
                                                'keyword2'=>['value'=>$deviceInfo['name'],'color'=>'#173177'],    //地点 (必须)
                                                'keyword3'=>['value'=>'人脸识别考勤','color'=>'#173177'],  //预警类型 (必须)
                                                'remark'=>['value'=>$remark,'color'=>'#000'] //备注
                                            ]
                                        ];

                                        $result = WeChat::pushmsg($postdata, $wxConfig['wx_appid'], $wxConfig['wx_secret']);
                                        $attendSendObj = new AttendSendModel();
                                        $up_data = [];
                                        $up_data['sendnum'] = $data['sendnum'] + 1;
                                        $up_data['response'] = $result;
                                        $up_where = [];
                                        $up_where['id'] = $sendRes;

                                        if($result == 'ok'){
                                            //推送成功，更新数据
                                            $up_data['updatetime'] = time();
                                            $up_data['status'] = 3;
                                        }else{
                                            //失败更新数据
                                            $up_data['failtime'] = time();
                                            $up_data['status'] = -1;
                                        }
                                        $attendSendObj->update($up_data, $up_where);
                                    }else{
                                        $postdata = [
                                            'touser' => $staff['openid'], //接收者openid , 必须
                                            'template_id'=> $wxConfig['templed_id'], //模板ID, 必须
                                            'url'=> ($basePath['wxPath'].'attend?ids='. $sendRes.'&token='.$wxConfig['token']), //模板跳转链接（海外帐号没有跳转能力） , 非必须
                                            'data'=>[ //消息数据,必须,数组里键名不能变,键值自由组装
                                                'first'=>['value'=> $first , 'color'=>'#173177'], //您有一条预警信息
                                                'keyword1'=>['value'=>date('Y-m-d H:i', $resdata['capinttime']),'color'=>'#173177'],  //学校 (必须)
                                                'keyword2'=>['value'=>$deviceInfo['name'],'color'=>'#173177'],    //地点 (必须)
                                                'keyword3'=>['value'=>'人脸识别考勤','color'=>'#173177'],  //预警类型 (必须)
                                                'remark'=>['value'=>$remark,'color'=>'#000'] //备注
                                            ]
                                        ];
                                        $sendurl = $wxConfig['api_url'].$basePath['wxpushPath'];
                                        $sdata = [];
                                        $sdata['sole'] = $wxConfig['token'];
                                        $sdata['info'] = $postdata;
                                        $sdata['timestamp'] = time();
                                        $sdata['sign'] = Utils::makeSignWechat($sdata, $wxConfig['token']);
                                        $sendData = json_encode($sdata);
                                        $head = [];
                                        $head['Content-Type'] = 'application/json;charset=utf-8';
                                        $curlObj = new Curl();
                                        $result = $curlObj->request('POST', $sendurl, $sendData, $head);
                                        $attendSendObj = new AttendSendModel();
                                        $up_data = [];
                                        $up_data['sendnum'] = $data['sendnum'] + 1;
                                        $up_data['response'] = $result;
                                        $up_where = [];
                                        $up_where['id'] = $sendRes;
                                        $json_result = json_decode($result, true);
                                        if(isset($json_result['code']) && ($json_result['code'] == 1)){
                                            //推送成功，更新数据
                                            $up_data['updatetime'] = time();
                                            $up_data['status'] = 3;
                                        }else{
                                            //失败更新数据
                                            $up_data['failtime'] = time();
                                            $up_data['status'] = -1;
                                        }
                                        $attendSendObj->update($up_data, $up_where);
                                    }
                                }
                            }
                        }
                    }
                }

            });
        }

    }

    // 创建数据表
    public function createTable($tableName, $tableName2)
    {
        $queryBuild = new QueryBuilder();
        $isset_sql = "SHOW TABLES LIKE '{$tableName}'";
        $queryBuild->raw($isset_sql);

        $model = DbManager::getInstance()->query($queryBuild, true, 'default');
        $isset = $model->getResult();

        if (!$isset) {
            $create_sql = "CREATE TABLE IF NOT EXISTS `{$tableName}` (
                            `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',
                            `school_code` VARCHAR(100) NOT NULL COMMENT '学校唯一编码',
                            `device_id` VARCHAR(32) NOT NULL COMMENT '来自设备DeviceId字段',
                            `device_uuid` VARCHAR(32) NULL DEFAULT NULL COMMENT '设备唯一编号',
                            `person_type` SMALLINT(2) NULL DEFAULT NULL COMMENT '名单类型：0 陌生人 1 黑名单 2 员工名单 3 VIP名单',
                            `name` VARCHAR(64) NULL DEFAULT NULL COMMENT '人员名称',
                            `numbers` VARCHAR(64) NULL DEFAULT NULL COMMENT '工号',
                            `compare_result` FLOAT(5,3) NULL DEFAULT NULL COMMENT '比对结果，即相似度',
                            `capture_time` INT(10) NULL DEFAULT NULL COMMENT '抓拍时间',
                            `send_time` INT(10) NULL DEFAULT NULL COMMENT '抓拍上传的发送时间',
                            `face_id` INT(10) UNSIGNED NULL DEFAULT NULL COMMENT '人员id，若上传请求faceid不存在，则使用设备faceid',
                            `device_face_id` INT(10) UNSIGNED NULL DEFAULT NULL COMMENT '设备faceid',
                            `face_quality` INT(8) NULL DEFAULT NULL COMMENT '图片质量',
                            `liveness` SMALLINT(2) NULL DEFAULT NULL COMMENT '人脸活体检测： 0非活体 1活体',
                            `imgpath` VARCHAR(128) NULL DEFAULT NULL COMMENT '上传的抓拍图片路径',
                            `imgexpath` VARCHAR(128) NULL DEFAULT NULL COMMENT '人脸背景图路径',
                            `face_feature` MEDIUMTEXT NULL,
                            `sub_device_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '设备连接的子设备ip地址',
                            `temper` VARCHAR(10) NULL DEFAULT NULL COMMENT '抓拍的人脸体温',
                            `etemper` VARCHAR(10) NOT NULL DEFAULT '' COMMENT '环境温度',
                            `channel` SMALLINT(255) NULL DEFAULT NULL COMMENT 'NVR通道号',
                            `create_time` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '添加时间',
                            `mark` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' COMMENT '有效标识(1正常 0删除)',
                            `status` SMALLINT(2) NULL DEFAULT NULL,
                            `device_remark` VARCHAR(32) NOT NULL,
                            PRIMARY KEY (`id`) USING BTREE
                        )
                        COMMENT='设备抓拍记录表'
                        COLLATE='utf8_general_ci'
                        ENGINE=InnoDB
                        ;";

            $queryBuild = new QueryBuilder();
            $queryBuild->raw($create_sql);
            $model = DbManager::getInstance()->query($queryBuild, true, 'default');
        }

        $isset_sql2 = "SHOW TABLES LIKE '{$tableName2}'";
        $queryBuild2 = new QueryBuilder();
        $queryBuild2->raw($isset_sql2);

        $model = DbManager::getInstance()->query($queryBuild2, true, 'default');
        $isset2 = $model->getResult();

        if (!$isset2) {
            $create_sql2 = "CREATE TABLE IF NOT EXISTS `{$tableName2}` (
                            `compare_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',
                            `school_code` VARCHAR(100) NOT NULL COMMENT '学校唯一编码',
                            `face_position` VARCHAR(32) NULL DEFAULT NULL COMMENT '人脸坐标',
                            `visit_count` INT(10) NULL DEFAULT NULL COMMENT '比对成功计数，比对成功才有该字段',
                            `alarm_event` TINYINT(4) NULL DEFAULT NULL COMMENT '报警事件 0：不报警 1：黑名单报警 2：白名单报警 3：VIP名单报警 4：非白名单报警',
                            `attr_age` TINYINT(4) NULL DEFAULT NULL COMMENT '人脸属性，年龄',
                            `attr_gender` TINYINT(4) NULL DEFAULT NULL COMMENT '人脸属性，性别',
                            `attr_glasses` TINYINT(4) NULL DEFAULT NULL COMMENT '人脸属性，是否带眼镜',
                            `attr_mask` TINYINT(4) NULL DEFAULT NULL COMMENT '人脸属性，是否带面具',
                            `attr_beard` TINYINT(4) NULL DEFAULT NULL COMMENT '人脸属性，是否留胡子',
                            `attr_race` TINYINT(4) NULL DEFAULT NULL COMMENT '人脸属性，肤色 1黄种人，2黑种人，3白种人',
                            `attr_emotion` TINYINT(4) NULL DEFAULT NULL COMMENT '表情 1：生气；2：高兴；3：悲伤；4：平静；5：惊讶',
                            `device_mac` VARCHAR(64) NULL DEFAULT NULL COMMENT '设备mac',
                            PRIMARY KEY (`compare_id`) USING BTREE
                        )
                        COMMENT='设备抓拍记录详情表'
                        COLLATE='utf8_general_ci'
                        ENGINE=InnoDB
                        ;";

            $queryBuild2 = new QueryBuilder();
            $queryBuild2->raw($create_sql2);
            $model = DbManager::getInstance()->query($queryBuild2, true, 'default');
        }
    }

}